package com.systop.ltbook.book.press.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.systop.core.ApplicationException;
import com.systop.core.service.BaseGenericsManager;
import com.systop.ltbook.book.press.model.Press;
import com.systop.ltbook.book.util.StringAlpha;

/**
 * 出版社管理类
 * 
 * @author DU
 */
@SuppressWarnings("unchecked")
@Service
public class PressManager extends BaseGenericsManager<Press> {
	
	//用户出版社前台页面查询;
	private String a2z = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";

	/**
	 * 保存出版社，不允许名称重复
	 */
	@Transactional
	public void save(Press press) {
		if (StringUtils.isNotEmpty(press.getName())) {
			StringAlpha s2a = new StringAlpha();
			press.setCharName(s2a.String2Alpha(press.getName())); 
			//logger.debug("{} 的首字母：{}", press.getName(), sa.String2Alpha(press.getName()));
			//if (getDao().exists(press, "name")) {
			//	throw new ApplicationException("出版社'" + press.getName() + "'已存在。");
			//}
		}
		super.save(press);
	}

	/**
	 * 取得所有的出版社
	 */
	public Map<String, List<Press>> getAllGroupByCharName() {
		String[] a2zArray = a2z.split(",");
		Map<String, List<Press>> m = new HashMap<String, List<Press>>();
		for (String charName : a2zArray){
			m.put(charName, getByFirstCharName(charName));
		}
		return m;
	}
	
	/**
	 * 取得所有的出版社
	 */
	public List<Map> getAllpresses() {
		List list = this.getDao().query("from Press p order by p.charName asc");
		if (CollectionUtils.isNotEmpty(list)) {
			return toMapArray(list);
		}
		return list;
	}
	
	/**
	 * 根据首字母第一位查询。
	 * @param firstCharName
	 * @return
	 */
	public List<Press> getByFirstCharName(String firstCharName){
		return query("from Press p where p.charName like ? order by p.charName asc", firstCharName + "%");
	}

	/**
	 * 将list中的对象转换为Map对象
	 * 
	 * @param list
	 * @return list of map
	 */
	private static List<Map> toMapArray(List<Press> list) {
		List<Map> result = new ArrayList(list.size());
		for (Press press : list) {
			Map<String, Comparable> item = new HashMap<String, Comparable>();
			item.put("prId", press.getId());
			item.put("prName", press.getName());
			result.add(item);
		}
		return result;
	}

	public Press getPressById(Integer pressId) {
		return getDao().get(Press.class, pressId);
	}
}
